﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.PhysicalExaminationItem;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.PhysicalExaminationItem
{
    /// <summary>
    /// 项目添加处理程序
    /// </summary>
    public class AddPhysicalExaminationItemHandler : IRequestHandler<AddPhysicalExaminationItemCommand, APIResult<int>>
    {
        private readonly IBaseRepository<PhysicalExaminationItems> baseRepository;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepository">仓储</param>
        /// <param name="mapper">映射</param>
        public AddPhysicalExaminationItemHandler(IBaseRepository<PhysicalExaminationItems> baseRepository, IMapper mapper)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理请求并返回结果
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">参数</param>
        /// <returns></returns>
        public async Task<APIResult<int>> Handle(AddPhysicalExaminationItemCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();

                var model = mapper.Map<PhysicalExaminationItems>(request);
                model.ProjectNo = GenerateProjectNumber();
                model.IsDeleted = false;
                model.ProjectStatus = false;
                model.CreateTime = DateTime.Now;
                var dto = baseRepository.AddAsync(model).Result;

                if (dto > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = dto;
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "添加失败";
                    return await Task.FromResult(result);
                }
                return await Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 生成项目编号
        /// </summary>
        /// <returns></returns>
        public static string GenerateProjectNumber()
        {
            // 这里可以根据具体需求修改编号生成规则
            // 例如：当前日期 + 随机数
            string datePart = DateTime.Now.ToString("yyyyMMdd");
            string randomPart = new Random().Next(1000, 9999).ToString();
            return $"XMBH{datePart}{randomPart}";
        }

    }
}